package com.wanlian.jpush.service;

import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
import com.wanlian.common.TagObj;
import com.wanlian.common.UrlConfig;
import com.wanlian.json.JsonStringUtil;
import com.wanlian.util.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class PushUtils {
    @Autowired
    private UrlConfig urlConfig;

    // private boolean isProduct = false;

    private final int ALERT_TYPE = 7;

    /**
     * 给所有平台的所有用户发通知
     */
    public void sendAllsetNotification(boolean android, boolean ios, String message, String extMsgBody, boolean IsProduct) {
        JPushClient jpushClient = new JPushClient(urlConfig.getJpushUrlAppSerckey(), urlConfig.getJpushUrlAppKey());
        Map<String, String> extras = new HashMap<String, String>();
        // 添加附加信息
        extras.put("extMessage", extMsgBody);
        PushPayload payload = buildPushObject_all_alias_alert(android, ios, message, extras, IsProduct);
        try {
            PushResult result = jpushClient.sendPush(payload);
            System.out.println(result);
        } catch (APIConnectionException e) {
            System.out.println(e);
        } catch (APIRequestException e) {
            System.out.println(e);
            System.out.println("Error response from JPush server. Should review and fix it. " + e);
            System.out.println("HTTP Status: " + e.getStatus());
            System.out.println("Error Code: " + e.getErrorCode());
            System.out.println("Error Message: " + e.getErrorMessage());
            System.out.println("Msg ID: " + e.getMsgId());
        }
    }

    /**
     * 给所有平台的所有用户发通知
     */
    public void sendAllsetNotification(String message, String extMsgBody, boolean IsProduct) {
        // JPushClient jpushClient = new
        // JPushClient(urlConfig.getJpushUrlAppSerckey(),
        // urlConfig.getJpushUrlAppKey());
        JPushClient jpushClient = new JPushClient("278e4019940b2abdefe72631", "e02279918f1b7f054573c247");
        Map<String, String> extras = new HashMap<String, String>();
        // 添加附加信息
        extras.put("extMessage", extMsgBody);
        PushPayload payload = buildPushObject_all_alias_alert(message, extras, IsProduct);
        try {
            PushResult result = jpushClient.sendPush(payload);
            System.out.println(result);
        } catch (APIConnectionException e) {
            System.out.println(e);
        } catch (APIRequestException e) {
            System.out.println(e);
            System.out.println("Error response from JPush server. Should review and fix it. " + e);
            System.out.println("HTTP Status: " + e.getStatus());
            System.out.println("Error Code: " + e.getErrorCode());
            System.out.println("Error Message: " + e.getErrorMessage());
            System.out.println("Msg ID: " + e.getMsgId());
        }
    }

    /**
     * 给所有平台的所有用户发消息
     *
     * @param message
     * @author WangMeng
     * @date 2017年1月13日
     */
    public void sendAllMessage(String message, boolean IsProduct) {
        JPushClient jpushClient = new JPushClient(urlConfig.getJpushUrlAppSerckey(), urlConfig.getJpushUrlAppKey());
        Map<String, String> extras = new HashMap<String, String>();
        // 添加附加信息
        extras.put("extMessage", "我是额外透传的消息");
        PushPayload payload = buildPushObject_all_alias_Message(message, extras, IsProduct);
        try {
            PushResult result = jpushClient.sendPush(payload);
            System.out.println(result);
        } catch (APIConnectionException e) {
            System.out.println(e);
        } catch (APIRequestException e) {
            System.out.println(e);
            System.out.println("Error response from JPush server. Should review and fix it. " + e);
            System.out.println("HTTP Status: " + e.getStatus());
            System.out.println("Error Code: " + e.getErrorCode());
            System.out.println("Error Message: " + e.getErrorMessage());
            System.out.println("Msg ID: " + e.getMsgId());
        }
    }

    /**
     * 发送通知
     *
     * @param message
     * @param extras
     * @return
     * @author WangMeng
     * @date 2017年1月13日
     */
    private PushPayload buildPushObject_all_alias_alert(boolean android, boolean ios, String message, Map<String, String> extras, boolean IsProduct) {
        Notification.Builder builder = Notification.newBuilder().setAlert(message);
        Platform platform = Platform.all();
        if (android) {
            platform = Platform.android();
            builder = builder.addPlatformNotification(AndroidNotification.newBuilder().addExtras(extras).setAlertType(ALERT_TYPE).build());
        }
        if (ios) {
            platform = Platform.ios();
            builder = builder.addPlatformNotification(IosNotification.newBuilder().addExtras(extras).setContentAvailable(true).build());
        }
        if (android & ios) {
            platform = Platform.all();
        }
        Notification notification = builder.build();

        return PushPayload.newBuilder().setPlatform(platform)
                // 设置平台
                .setAudience(Audience.all())
                // 按什么发送 tag alia
                .setNotification(notification)
                // 发送消息
                .setOptions(Options.newBuilder().setApnsProduction(IsProduct).build()).build();
        // 设置ios平台环境 True 表示推送生产环境，False 表示要推送开发环境 默认是开发
    }

    /**
     * 发送通知
     *
     * @param message
     * @param extras
     * @return
     * @author WangMeng
     * @date 2017年1月13日
     */
    private PushPayload buildPushObject_all_alias_alert(String message, Map<String, String> extras, boolean IsProduct) {
        return PushPayload.newBuilder().setPlatform(Platform.all())
                // 设置平台
                .setAudience(Audience.all())
                // 按什么发送 tag alia
                .setNotification(Notification.newBuilder().setAlert(message).addPlatformNotification(AndroidNotification.newBuilder().addExtras(extras).build())
                        .addPlatformNotification(IosNotification.newBuilder().addExtras(extras).build()).build())
                // 发送消息
                .setOptions(Options.newBuilder().setApnsProduction(IsProduct).build()).build();
        // 设置ios平台环境 True 表示推送生产环境，False 表示要推送开发环境 默认是开发
    }

    /**
     * 发送透传消息
     *
     * @param message
     * @param extras
     * @return
     * @author WangMeng
     * @date 2017年1月13日
     */
    private PushPayload buildPushObject_all_alias_Message(String message, Map<String, String> extras, boolean IsProduct) {
        return PushPayload.newBuilder().setPlatform(Platform.all())
                // 设置平台
                .setAudience(Audience.all())
                // 按什么发送 tag alia
                .setMessage(Message.newBuilder().setMsgContent(message).addExtras(extras).build())
                // 发送通知
                .setOptions(Options.newBuilder().setApnsProduction(IsProduct).build()).build();
        // 设置ios平台环境 True 表示推送生产环境，False 表示要推送开发环境 默认是开发
    }

    /**
     * 客户端 给所有平台的一个或者一组用户发送信息
     */
    public void sendAlias(String message, List<String> aliasList, boolean IsProduct) {
        JPushClient jpushClient = new JPushClient(urlConfig.getJpushUrlAppSerckey(), urlConfig.getJpushUrlAppKey());
        Map<String, String> extras = new HashMap<String, String>();
        // 添加附加信息
        extras.put("extMessage", "我是额外的消息--sendAlias");
        PushPayload payload = allPlatformAndAlias(message, extras, aliasList, IsProduct);
        try {
            PushResult result = jpushClient.sendPush(payload);
            System.out.println(result);
        } catch (APIConnectionException e) {
            System.out.println(e);
        } catch (APIRequestException e) {
            System.out.println(e);
            System.out.println("Error response from JPush server. Should review and fix it. " + e);
            System.out.println("HTTP Status: " + e.getStatus());
            System.out.println("Error Code: " + e.getErrorCode());
            System.out.println("Error Message: " + e.getErrorMessage());
            System.out.println("Msg ID: " + e.getMsgId());
        }
    }

    /**
     * 极光推送：生成向一个或者一组用户发送的消息。
     */
    private PushPayload allPlatformAndAlias(String alert, Map<String, String> extras, List<String> aliasList, boolean IsProduct) {

        return PushPayload.newBuilder().setPlatform(Platform.all()).setAudience(Audience.alias(aliasList))
                .setNotification(Notification.newBuilder().setAlert(alert).addPlatformNotification(AndroidNotification.newBuilder().setAlertType(ALERT_TYPE).build())
                        .addPlatformNotification(IosNotification.newBuilder().setContentAvailable(true).build()).build())
                .setOptions(Options.newBuilder().setApnsProduction(IsProduct).build()).build();
    }

    /**
     * 客户端 给平台的一个或者一组标签发送消息。
     */
    public void sendTag(String message, String messageId, String type, List<String> tagsList, boolean IsProduct) {
        JPushClient jpushClient = new JPushClient(urlConfig.getJpushUrlAppSerckey(), urlConfig.getJpushUrlAppKey());
        // 附加字段
        Map<String, String> extras = new HashMap<String, String>();
        extras.put("messageId", messageId);
        extras.put("typeId", type);

        PushPayload payload = allPlatformAndTag(message, extras, tagsList, IsProduct);
        try {
            PushResult result = jpushClient.sendPush(payload);
            System.out.println(result);
        } catch (APIConnectionException e) {
            System.out.println(e);
        } catch (APIRequestException e) {
            System.out.println(e);
            System.out.println("Error response from JPush server. Should review and fix it. " + e);
            System.out.println("HTTP Status: " + e.getStatus());
            System.out.println("Error Code: " + e.getErrorCode());
            System.out.println("Error Message: " + e.getErrorMessage());
            System.out.println("Msg ID: " + e.getMsgId());
        }
    }

    /**
     * 极光推送：生成向一组标签进行推送的消息。
     */
    private PushPayload allPlatformAndTag(String alert, Map<String, String> extras, List<String> tagsList, boolean IsProduct) {

        return PushPayload.newBuilder().setPlatform(Platform.android_ios()).setAudience(Audience.tag(tagsList))
                .setNotification(Notification.newBuilder().setAlert(alert).addPlatformNotification(AndroidNotification.newBuilder().addExtras(extras).build())
                        .addPlatformNotification(IosNotification.newBuilder().addExtras(extras).setContentAvailable(true).build()).build())
                .setOptions(Options.newBuilder().setApnsProduction(IsProduct).build()).build();
    }

    public static void main(String[] args) {
        // new PushUtil().sendAll("这是java后台发送的一个通知。。。。");
        // List<String> sendAlias = new ArrayList<>();
        // sendAlias.add("1001");
        // new PushUtil().sendAlias("这是java后台发送的一个按照alia的通知", sendAlias);

        // new PushUtils().sendAllMessage("这是后台发送的透传消息");
        // TagObj tagObj = new TagObj();
        // tagObj.setnType(ConstantCode.FORUM_EDIT_MSG);
        // tagObj.setContent("这是后台发送的透传消息");
        // String sourceType = JsonStringUtil.writeValueAsString(tagObj);
        // new PushUtils().sendAllsetNotification("版块调整测试", sourceType);

//        TagObj tagObj = new TagObj();
//        // tagObj.setnType(ConstantCode.FORUM_EDIT_MSG);
//        tagObj.setContent("后台消息测试");
//        String sourceType = JsonStringUtil.writeValueAsString(tagObj);
        //new PushUtils().sendAllsetNotification("后台消息测试", sourceType, true);

        List<String> alist = new ArrayList<>();
        alist.add("16d695824a9d48e4a744129da38adf04");
        new PushUtils().sendAlias("后台消息测试", alist, false);

    }
}
